import { createFetch } from '@vueuse/core'
import { destr } from 'destr'
import {toast} from "@/@core/components/app-sonner/libs"
import {router} from '@/plugins/1.router'
import { cookieRef } from '@layouts/stores/config'

export const useApi = createFetch({
  baseUrl: import.meta.env.VITE_API_BASE_URL || '/api',
  fetchOptions: {
    headers: {
      Accept: 'application/json',
    },
  },
  options: {
    refetch: true,
    async beforeFetch({ url,options }) {
      const accessToken = localStorage.getItem("accessToken") || sessionStorage.getItem("accessToken")
      const contentLang = cookieRef('content-language','zh_CN')
      if (accessToken) {
        options.headers = {
          ...options.headers,
          'Content-Language': contentLang.value,
          Authorization: `Bearer ${accessToken}`,
          clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
        }
      }
      if (options.method === 'GET' && options.query) {
        let requestUrl = url + '?' + tansParams(options.query);
        url = requestUrl.slice(0, -1);
        options.query = {};
      }
      return { url,options }
    },
    afterFetch(ctx) {
      const { data, response } = ctx
      // Parse data if it's JSON
      let parsedData = null
      try {
        parsedData = destr(data)
      }
      catch (error) {
        console.error(error)
      }
      if (parsedData.code === 401) {
        router.replace({
          path: '/login',
          query: {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
          }})
        return Promise.reject(new Error('登陆状态已过期,请重新登录'))
      }
      return { data: parsedData, response }
    },
    onFetchError(ctx) {
      let {message} = ctx.error
      if (message == 'Internal Server Error') {
        message = '后端接口连接异常';
      } else if (message.includes('timeout')) {
        message = '系统接口请求超时';
      } else if (message.includes('Request failed with status code')) {
        message = '系统接口' + message.substr(message.length - 3) + '异常';
      }
      toast(message,{
        cardProps: {
          color: 'error',
        },
        prependIcon: 'tabler-ban'
      })
      return Promise.reject(ctx.error)
    },
  },
})
